package com.haredot.controller;

import com.haredot.constraint.SysConst;
import com.haredot.dto.UserLoginDTO;
import com.haredot.entity.User;
import com.haredot.service.LoginService;
import com.haredot.vo.R;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

@Controller
public class LoginController {

    @Resource
    private LoginService loginService;

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public R<?> login(@Valid UserLoginDTO userLoginDTO, HttpSession session) {
        // 处理登录逻辑
        R<User> ret = loginService.loginByRole(userLoginDTO);

        if (ret.getStatus()) {
            // 如果登录成功、将登录信息记录到 Session中
            session.setAttribute(SysConst.CURRENT_USER, ret.getData());
        }
        return ret;
    }


    @GetMapping("/logout")
    public String login(HttpSession session) {
        session.removeAttribute(SysConst.CURRENT_USER);
        // 退出登录后，跳转到登录页面
        return "redirect:/login";
    }
}
